package model.audio;
import java.io.ByteArrayOutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.ArrayList;

import javax.sound.midi.ControllerEventListener;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Control;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.Control.Type;


public class Player{
	
	private SourceDataLine line=null;
	private int bufferSize;
	private FloatControl volctrl=null;
	private InetSocketAddress client=null;
	private DataLine.Info info=null;
	
	protected long audioStartTime=0;
	protected boolean isTalk=false;
	
	public static final float SAMPLE_RATE=4096;
	public static final int SAMPLE_SIZE_IN_BITS=8;
	public static final int CHANNELS=1;

	public Player(InetSocketAddress ad,float volume,long audioStartTime){
        client=ad;
		bufferSize=AudioCaptureModel.BUFFER_LENGTH*10;
		AudioFormat format =new AudioFormat(SAMPLE_RATE,SAMPLE_SIZE_IN_BITS,CHANNELS,true,true);
		info = new DataLine.Info(SourceDataLine.class,format);
        try {
        	line = (SourceDataLine) AudioSystem.getLine(info);
			line.open(format,bufferSize);
			line.start();
        } catch (LineUnavailableException e) {
        	e.printStackTrace();
        }
		volctrl=(FloatControl)line.getControl(FloatControl.Type.MASTER_GAIN);    //-80~6
		setVolume(volume);
		this.audioStartTime=audioStartTime;
	}
	
	public void play(byte data[]){
		line.flush();	
		line.write(data, 0, data.length);
	}

	public void setVolume(float value){
		volctrl.setValue(value);   //-80~6
	}

	public InetSocketAddress getClient() {
		return client;
	}
	
	public void close(){
		line.stop();
		line.close();
	}

}
